# coding:utf-8
# author    : ['王稣胤 820390693@qq.com', ]
# data      : 2020/3/6 13:17
# software  : PyCharm
# python    : '3.5.3 64bit'
# file      : wsyffw_dbop.py
"""
说明文档：
这里用的原生的sqlalchemy
"""

import logging

logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    level=logging.DEBUG)

from sqlalchemy import create_engine
from sqlalchemy.exc import *
from sqlalchemy.orm import sessionmaker

from contextlib import contextmanager


@contextmanager
def auto_session(engine):
    ses = sessionmaker(engine)()
    try:
        yield ses
    except Exception as err:
        logging.debug('提交出错，回滚')
        ses.rollback()
        raise err

    finally:
        logging.debug('关闭会话')
        ses.close()


def __get_connect_db_cmd(username, password, host, database, port, charset):
    return 'mysql+mysqlconnector://{username}:{password}@{host}:{port}/{database}?charset={charset}'.format(
        username=username,
        password=password,
        host=host,
        database=database,
        port=port,
        charset=charset,
    )


def create_sqlalchemy_engine(username, password, host, database, port, charset):
    return create_engine(__get_connect_db_cmd(username, password, host, database, port, charset))

# def get_object_group_preview_image_fp(object_group_number):
#
#     with auto_session(engine) as ses:
#         sql = '''
#         select preview_image from object_group where number={!r}
#         '''.format(object_group_number)
#
#         res = ses.execute(sql)
#         res = res.fetchall()
#     fp =lib.decode_if_bytearray( res[0][0])
#     return  fp
